package org.devf.fork.imsimulator.http;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.URLUtil;
import org.devf.fork.imsimulator.http.pojo.ChatImageDto;
import org.devf.fork.imsimulator.model.HttpConstant;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * DefaultHttpClient related
 *
 * @author wanghuafu
 * @since 1.0  2023/9/12 17:41
 */
public class ImageFileHttpClient extends DefaultHttpClient {


    public String postImage(String url, ChatImageDto chatImageDto) {
        Map<String, String> params = new HashMap<>();
        params.put("bizType", chatImageDto.getBizType());
        params.put("destId", chatImageDto.getDestId() + "");
        String urlParams = URLUtil.buildQuery(params, Charset.defaultCharset());
        return execute(url + "?" + urlParams, HttpConstant.ReqMethod.POST, chatImageDto);
    }


    @Override
    public String execute(String url, String method, Object body) {
        // 获取输出流
        Assert.isTrue(body instanceof ChatImageDto, "文件名不能为空");
        ChatImageDto p = null;
        if (body instanceof ChatImageDto) {
            p = (ChatImageDto) body;
        }

        if (!url.startsWith("/")) {
            url = "/" + url;
        }
        HttpURLConnection connection = null;
        DataOutputStream wr = null;
        int responseCode = 0;
        // 生成随机分隔符
        String boundary = UUID.randomUUID().toString();

        try {
            // 打开 HTTP 连接
            connection = (HttpURLConnection) new URL(HttpConstant.WebUrl.ROOT_PATH + url).openConnection();
            // 设置请求方法（GET、POST、等）
            connection.setRequestMethod(method);
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); // 替换为合适的分隔符
            // 可选：设置请求头
            addHeader(connection);
            processBefore(url, body, headerMap);

            /* ==========传输请求体开始=========*/
            wr = new DataOutputStream(connection.getOutputStream());
            PrintWriter writer = new PrintWriter(new OutputStreamWriter(wr, StandardCharsets.UTF_8), true);
            // 添加文件参数
            writer.append("--" + boundary + "\r\n");
            writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"").append(p.getFile().getName()).append("\"\r\n");
            writer.append("Content-Type: image/png\r\n\r\n");
            writer.flush();

            FileInputStream fileInputStream = new FileInputStream(p.getFile());
            byte[] buffer = new byte[2048];
            int bytesRead;
            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                wr.write(buffer, 0, bytesRead);
            }
            wr.flush();
            IoUtil.close(fileInputStream);
            // 请求体结束
            writer.append("\r\n");
            writer.flush();
            writer.append("--"+boundary+"--\r\n");
            writer.close();
            /* ==========请求体内容正式结束=========*/

            // 发送请求并获取响应码
            responseCode = connection.getResponseCode();

            // 读取响应数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            IoUtil.close(reader);

            processAfter(url, body, headerMap, response);
            return response.toString(); //怎么不封装成T ,泛型转化异常？？模块化结构的锅。

        } catch (IOException e) {
            super.processError(url, body, headerMap, responseCode, e.getMessage());
        } finally {
            if (null != connection) {
                connection.disconnect();
            }
            IoUtil.close(wr);
        }
        return null;
    }

    private void addHeader(HttpURLConnection connection) {
        if (!headerMap.isEmpty()) {
            headerMap.forEach(connection::setRequestProperty);
        }
    }


}
